import json
import logging
from http.server import HTTPServer, BaseHTTPRequestHandler
import traceback
import os
import sys
import http.server
import socketserver
from urllib.parse import urlparse, parse_qs
from datetime import datetime

# 添加当前目录到路径
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(current_dir)

# 创建日志目录
logs_dir = os.path.join(current_dir, 'logs')
os.makedirs(logs_dir, exist_ok=True)

# 配置日志
log_file = os.path.join(logs_dir, f'audit_service_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log')

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    handlers=[
        logging.FileHandler(log_file, encoding='utf-8'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

logger.info(f"日志文件创建于: {log_file}")

# 导入服务
try:
    from app.services.sensitive_service import sensitive_word_service
    from app.services.audit_service import audit_service
    logger.info("成功导入审核服务和敏感词服务")
except Exception as e:
    logger.error(f"导入服务失败: {str(e)}")
    logger.error(traceback.format_exc())
    sys.exit(1)

class AuditServiceHandler(http.server.BaseHTTPRequestHandler):
    def _set_response(self, status_code=200):
        self.send_response(status_code)
        self.send_header('Content-type', 'application/json')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, Cache-Control, Pragma, X-Request-ID')
        self.end_headers()
    
    def do_OPTIONS(self):
        self._set_response()
    
    def do_POST(self):
        client_address = self.client_address[0]
        logger.info(f"收到来自 {client_address} 的POST请求: {self.path}")
        
        try:
            parsed_path = urlparse(self.path)
            path = parsed_path.path.lower()
            
            # 记录请求头
            headers = {}
            for header, value in self.headers.items():
                headers[header] = value
            logger.debug(f"请求头: {json.dumps(headers, ensure_ascii=False)}")
            
            # 读取请求体
            content_length = int(self.headers['Content-Length']) if 'Content-Length' in self.headers else 0
            post_data = self.rfile.read(content_length) if content_length > 0 else b'{}'
            
            try:
                request_json = json.loads(post_data.decode('utf-8'))
                logger.debug(f"收到请求: PATH: {path}, DATA: {json.dumps(request_json, ensure_ascii=False)}")
            except json.JSONDecodeError:
                logger.warning(f"无法解析JSON请求体: {post_data.decode('utf-8', errors='replace')}")
                request_json = {}
            
            # 处理ping请求 (健康检查)
            if path == '/ping':
                response = {"status": "ok", "message": "service is running"}
                self._set_response()
                self.wfile.write(json.dumps(response).encode('utf-8'))
                return
                
            # 处理健康检查请求
            if path == '/health' or path == '/healthz':
                response = {"status": "healthy", "version": "2.0.0"}
                self._set_response()
                self.wfile.write(json.dumps(response).encode('utf-8'))
                return
            
            response = {}
            
            # 1. 处理审核请求
            if path == '/api/audit':
                logger.info(f"处理审核请求: postId={request_json.get('postId')}")
                
                # 将camelCase转为snake_case
                snake_case_request = {
                    'post_id': request_json.get('postId'),
                    'title': request_json.get('title'),
                    'content': request_json.get('content'),
                    'user_id': request_json.get('userId')
                }
                
                # 打印请求信息
                logger.info(f"审核请求内容: title={snake_case_request['title']}, content长度={len(snake_case_request['content']) if snake_case_request['content'] else 0}")
                
                # 调用审核服务
                try:
                    audit_result = audit_service.audit_content(snake_case_request)
                    logger.info(f"审核完成: post_id={audit_result.get('post_id')}, 结果={audit_result.get('audit_result')}")
                except Exception as e:
                    logger.error(f"调用审核服务异常: {str(e)}")
                    logger.error(traceback.format_exc())
                    raise
                
                # 将snake_case转回camelCase (Java客户端需要)
                response = {
                    'postId': audit_result.get('post_id'),
                    'auditResult': audit_result.get('audit_result'),
                    'confidence': audit_result.get('confidence'),
                    'reasons': audit_result.get('reasons'),
                    'suggestion': audit_result.get('suggestion')
                }
            
            # 2. 处理反馈请求
            elif path == '/api/feedback':
                logger.info(f"处理反馈请求: postId={request_json.get('postId')}")
                
                # 将camelCase转为snake_case
                snake_case_feedback = {
                    'post_id': request_json.get('postId'),
                    'admin_id': request_json.get('adminId'),
                    'ai_decision': request_json.get('aiDecision'),
                    'final_decision': request_json.get('finalDecision'),
                    'is_correct': request_json.get('isCorrect'),
                    'feedback': request_json.get('feedback')
                }
                
                # 调用反馈服务
                try:
                    result = audit_service.save_feedback(snake_case_feedback)
                    logger.info(f"反馈处理完成: post_id={snake_case_feedback['post_id']}, 结果={result}")
                except Exception as e:
                    logger.error(f"调用反馈服务异常: {str(e)}")
                    logger.error(traceback.format_exc())
                    raise
                
                response = {
                    'status': 'success' if result else 'error',
                    'message': '反馈已保存' if result else '保存反馈失败'
                }
            
            # 3. 处理未知路径
            else:
                logger.warning(f"未知路径请求: {path}")
                self._set_response(404)
                response = {
                    'status': 'error',
                    'message': '未找到请求路径'
                }
                self.wfile.write(json.dumps(response).encode('utf-8'))
                return
            
            logger.debug(f"响应数据: {json.dumps(response, ensure_ascii=False)}")
            
            # 发送响应
            self._set_response()
            response_json = json.dumps(response)
            self.wfile.write(response_json.encode('utf-8'))
            logger.info(f"请求处理完成: {path}, 响应大小={len(response_json)}")
        
        except Exception as e:
            logger.error(f"处理请求异常: {str(e)}")
            logger.error(traceback.format_exc())
            self._set_response(500)
            error_response = {
                'status': 'error',
                'message': f'服务器内部错误: {str(e)}'
            }
            self.wfile.write(json.dumps(error_response).encode('utf-8'))
    
    def log_message(self, format, *args):
        logger.info("%s - - [%s] %s" % (self.client_address[0], self.log_date_time_string(), format % args))

def run(host="0.0.0.0", port=8090):
    handler = AuditServiceHandler
    server_address = (host, port)
    try:
        httpd = socketserver.TCPServer(server_address, handler)
        logger.info(f"启动服务器在 http://{host}:{port}")
        httpd.serve_forever()
    except Exception as e:
        logger.error(f"启动服务器失败: {str(e)}")
        logger.error(traceback.format_exc())
        sys.exit(1)

if __name__ == "__main__":
    # 确保敏感词服务已初始化
    logger.info("初始化敏感词服务...")
    
    # 启动服务器
    logger.info("启动审核服务...")
    run() 